package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.NumericalLimitsPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.InstockDao;
import com.xbongbong.saas.domain.entity.InstockProductEntity;
import com.xbongbong.saas.domain.entity.ProductSerialFlowEntity;
import com.xbongbong.saas.domain.entity.ProductStockEntity;
import com.xbongbong.saas.domain.entity.ProductStockInfoEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.UpdateStockDataEntity;
import com.xbongbong.saas.domain.entity.ext.InstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.PurchaseInstockEnum;
import com.xbongbong.saas.enums.business.RefundInstockEnum;
import com.xbongbong.saas.enums.business.SerialEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.product.InstockProductEnum;
import com.xbongbong.saas.help.BatchKeyHelp;
import com.xbongbong.saas.help.DefaultAttrHelp;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InstockProductModel;
import com.xbongbong.saas.model.InstockSubDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductSerialFlowModel;
import com.xbongbong.saas.model.ProductStockModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 入库单
 * @author 吴峰
 * @version v1.0
 * @date 2019/2/18 15:26
 * @since v1.0
 */
@Service("instockModel")
public class InstockModelImpl implements InstockModel {

    @Resource
    private InstockDao instockDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private InstockSubDataModel instockSubDataModel;
    @Resource
    private DefaultAttrHelp defaultAttrHelp;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private InstockProductModel instockProductModel;
    @Resource
    private ProductSerialFlowModel productSerialFlowModel;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private ProductStockModel productStockModel;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private EsHelper esHelper;
    @Resource
    private CommonHelp commonHelp;

    @Override
    public InstockEntityExt getByKey(Long key, String corpid) {
        InstockEntityExt instockEntityExt = instockDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(instockEntityExt), IndexTypeEnum.IDX_SAAS_INSTOCK_SUB);
        return instockEntityExt;
    }

    /**
     * 根据data里某个条件搜索
     *
     * @param attr   data里属性
     * @param value  data里属性的值
     * @param param 参数
     */
    @Override
    public Integer getCountByOneCondition(String attr, Object value, Map<String, Object> param) {
        attr = "$." + attr;
        return instockDao.getCountByOneCondition(attr, value, param);
    }

    @Override
    public List<InstockEntityExt> getBySupplierId(Map<String, Object> param) {
        return instockDao.getBuSupplierId(param);
    }

    /**
     * @param param 参数集合
     * @return List<Long> 入库单参数集合
     */
    @Override
    public List<Long> findIds(Map<String, Object> param) {
        return instockDao.findIds(param);
    }

    @Override
    public Integer insert(InstockEntityExt entity) throws XbbException {
        // 先进行数据库的插入动作
        long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_INSTOCK_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer insertId = instockDao.insert(entity);

        // 插入ES
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_INSTOCK);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_INSTOCK_SUB);
        return insertId;
    }

    @Override
    public Integer update(InstockEntityExt entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_INSTOCK_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = instockDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_INSTOCK_SUB);

        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            success = instockDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新ES
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_INSTOCK);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);
        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    @Override
    public List<InstockEntityExt> findEntitys(Map<String, Object> param) {
        List<InstockEntityExt> entitys = instockDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_INSTOCK_SUB);
        }
        return entitys;
    }

    /**
     * 保存
     *
     * @param instock 数据
     */
    @Override
    public Integer save(InstockEntityExt instock) throws XbbException {
        if (instock.getId() == null || instock.getId().equals(0L)) {
            return insert(instock);
        }
        return update(instock);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return instockDao.getEntitysCount(param) ;
    }

    /**
     * 去掉特定的入库单 因为在其他model类中重复出现所以将其提取出来放在入库单model层中
     * @param instockIdList 入库单产品集合
     * @param instockIds 入库单产品集合
     * @date 2019/2/25 10:25
     * @author Jian.Wang
     */
    @Override
    public void removeInstock(List<Long> instockIdList,List<Long> instockIds) {
        if(instockIdList != null){
            Iterator<Long> it = instockIds.iterator();
            while(it.hasNext()){
                Long id = it.next();
                for(Long instockId : instockIdList){
                    if(id.equals(instockId)){
                        it.remove();
                    }
                }
            }
        }
    }

    @Override
    public Integer deleteBatch(List<Long> list, String corpid) throws XbbException {
        Integer integer = instockDao.deleteBatch(list, corpid);
        //ES根据id批量设置del=1
        paasEsModel.deleteBatch(list, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_INSTOCK);
        return integer;
    }

    @Override
    public Integer deleteBatchImmediately(List<Long> list, String corpid) throws XbbException {
        Integer integer = instockDao.deleteBatch(list, corpid);
        //ES根据id批量设置del=1
        paasEsModel.deleteBatch(list, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_INSTOCK, WriteRequest.RefreshPolicy.NONE);
        paasFormSubDataModel.deleteBatchByDataId(list, corpid, IndexTypeEnum.IDX_SAAS_INSTOCK_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_INSTOCK);
        paasEsModel.delete(deleteDTO);
        Integer integer = instockDao.deleteByKey(key, corpid);
        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_INSTOCK_SUB);
        return integer;
    }

    @Override
    public Integer updateBatchDataByType(List<UpdateStockDataEntity> updateDataList, String corpid) throws XbbException {
        Integer integer = instockDao.updateBatchDataByType(updateDataList, corpid);
        paasEsModel.updateBatchDataByType(updateDataList, IndexTypeEnum.IDX_SAAS_INSTOCK);
        return integer;
    }

    @Override
    public List<String> getCorpidList() {
        return instockDao.getCorpidList();
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateDataList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateDataList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateDataList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateDataList)) {
            StandardizeDataUtil.standardizeList(updateDataList);
            integer = instockDao.updateBatch(updateDataList, corpid);
            paasEsModel.updateBatchMuchField(updateDataList, IndexTypeEnum.IDX_SAAS_INSTOCK);
        }
        if (!subList.isEmpty()) {
            instockSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = instockDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_INSTOCK, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            instockSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer batchUpdateOwner(List<Long> dataIdList, String corpid, String userId, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer integer = instockDao.batchUpdateOwner(dataIdList, corpid, userId);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (Long id : dataIdList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid+"_"+id);
            Map<String, Object> map = new HashMap<>();
            map.put(FieldTypeEnum.OWNERID.getAlias(), userId);
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_INSTOCK);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList, refreshPolicy);
        return integer;
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return instockDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        formatExplainDTO.setEditFormat(true);
        formatAddExplain(formatExplainDTO);
        // 编辑时产品仓库不可以修改，审批编辑除外（同新建）
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        JSONObject data = formatExplainDTO.getResult();
        data.put(InstockEnum.TYPE.getAttr(),data.getString(InstockEnum.TYPE.getAttr()));
        Integer instockType = data.getInteger(InstockEnum.TYPE.getAttr());
        Integer linkBusinessType = InstockTypeEnum.getByCode(instockType).getBusinessType();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(fieldType, FieldTypeEnum.SELECT_PRODUCT.getType())) {
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
                if (Objects.isNull(formatExplainDTO.getFromCopy()) || !formatExplainDTO.getFromCopy()) {
                    fieldAttrEntity.setEditable(0);
                    List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                    subExplainList.forEach(item -> item.setEditable(0));
                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_MULTI.getType()) || Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())) {
                fieldAttrEntity.setEditable(0);
            }
            if (Objects.equals(attr, InstockEnum.WAREHOUSE_ID.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }else if (Objects.equals(attr, InstockEnum.TYPE.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }else if (Objects.equals(attr, InstockEnum.REF_ID.getAttr())) {
                fieldAttrEntity.setLinkedType(linkBusinessType);
            }else if (Objects.equals(attr, PurchaseInstockEnum.SUPPLIER_ID_LINKED_TEXT.getAttr()) && Objects.equals(instockType,InstockTypeEnum.PURCHASE_INSTOCK.getCode())){
                fieldAttrEntity.setEditable(0);
            }else if (Objects.equals(attr, InstockEnum.TIME.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }else if (Objects.equals(attr, RefundInstockEnum.OTHER_EXPENSE.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }else if (Objects.equals(attr, RefundInstockEnum.TOTAL_MONEY.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }
        }
    }

    @Override
    public Boolean formatAddExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        Integer businessType = formatExplainDTO.getBusinessType();
        String corpid = formatExplainDTO.getCorpid();
        int index = 0;
        int selectProductIndex = -1;
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            if (Objects.equals(fieldType, FieldTypeEnum.SELECT_PRODUCT.getType())) {
                selectProductIndex = index;
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
                if (Objects.equals(formatExplainDTO.getLinkBusinessType(), XbbRefTypeEnum.INVENTORY.getCode())) {
                    explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.INSTOCK, corpid, BasicConstant.ZERO, false);
                }else {
                    explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.INSTOCK, corpid, BasicConstant.ONE, false);
                }
                if (Objects.equals(formatExplainDTO.getBusinessType(), XbbRefTypeEnum.OTHER_INSTOCK.getCode()) && (Objects.equals(formatExplainDTO.getLinkBusinessType(), XbbRefTypeEnum.TRANSFER.getCode()) || Objects.equals(formatExplainDTO.getLinkBusinessType(), XbbRefTypeEnum.INVENTORY.getCode()))) {
                    List<? extends FieldAttrEntity> subFormArray = fieldAttrEntity.getSubForm().getItems();
                    Iterator<? extends FieldAttrEntity> iterator = subFormArray.iterator();
                    while (iterator.hasNext()) {
                        FieldAttrEntity subFormItem = iterator.next();
                        String attr = subFormItem.getAttr();
                        if (Objects.equals(attr, SelectProductEnum.BATCH.getAttr()) || Objects.equals(attr, SelectProductEnum.PRODUCE_DATE.getAttr()) || Objects.equals(attr, SelectProductEnum.GUARANTEE_PERIOD.getAttr())) {
                            subFormItem.setEditable(0);
                        }
                    }
                }
            }else if (Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.MANAGER_ID.getAttr())) {
                if(fieldAttrEntity.getDefaultAttr() == null || (fieldAttrEntity.getDefaultAttr() != null && CollectionUtils.isEmpty(fieldAttrEntity.getDefaultAttr().getDefaultList()))){
                    fieldAttrEntity.setDefaultAttr(defaultAttrHelp.setUserDefaultAttrPoJo(formatExplainDTO.getUserId(), formatExplainDTO.getLoginUser().getName(),formatExplainDTO.getLoginUser().getAvatar()));
                }
            }else if (!Objects.equals(formatExplainDTO.getEditFormat(), true) && Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.TYPE.getAttr())) {
                List<ItemPoJo> items = fieldAttrEntity.getItems();
                items.removeIf(item -> Objects.equals(Objects.toString(item.getValue()), Objects.toString(InstockTypeEnum.ASSEMBLE_INSTOCK.getCode())));
            }
            // 销售退货单处理精度、数值范围
            if (Objects.equals(businessType, XbbRefTypeEnum.REFUND_INSTOCK.getCode())
                    && (Objects.equals(fieldAttrEntity.getAttr(), RefundInstockEnum.PRODUCT_TOTAL.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), RefundInstockEnum.OTHER_EXPENSE.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), RefundInstockEnum.TOTAL_MONEY.getAttr()))) {
                if (selectProductIndex != -1) { // selectProductIndex未变动跳过
                    List<? extends FieldAttrEntity> subFormItems = explainList.get(selectProductIndex).getSubForm().getItems();
                    for (FieldAttrEntity subFormItem : subFormItems) {
                        if (Objects.equals(subFormItem.getAttr(), SelectProductEnum.PRICE.getAttr())) {
                            NumericalLimitsPoJo numericalLimits = new NumericalLimitsPoJo();
                            if (Objects.nonNull(subFormItem.getNumericalLimits())) {
                                numericalLimits.setMin(subFormItem.getNumericalLimits().getMin());
                                numericalLimits.setMax(subFormItem.getNumericalLimits().getMax());
                            }
                            fieldAttrEntity.setNumericalLimits(numericalLimits);
                            fieldAttrEntity.setNumericalLimitsFlag(subFormItem.getNumericalLimitsFlag());
                            fieldAttrEntity.setAccuracy(subFormItem.getAccuracy());
                            break;
                        }
                    }
                }
            }
            index++;
        }
        return !Objects.equals(formatExplainDTO.getBusinessType(),XbbRefTypeEnum.OTHER_INSTOCK.getCode()) || (Objects.nonNull(formatExplainDTO.getLinkBusinessType()));
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param formDataUpdateGetDTO saas编辑数据
     * @param result               要返回的jsonobject
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/22 15:28
     */
    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        // 格式化仓库字段
        showFormatHelp.formatLinkBusiness4Show(result, InstockEnum.WAREHOUSE_ID.getAttr(), InstockEnum.WAREHOUSE_ID_LINKED_TEXT.getAttr(), InstockEnum.WAREHOUSE_ID.getFieldType());
        // 展示供应商
        Integer businessType = formDataUpdateGetDTO.getBusinessType();
        InstockTypeEnum instockTypeEnum = InstockTypeEnum.getByStockBusinessType(businessType);
        switch (instockTypeEnum) {
            case PURCHASE_INSTOCK:
                showFormatHelp.formatLinkBusiness4Show(result, PurchaseInstockEnum.SUPPLIER_ID.getAttr(), PurchaseInstockEnum.SUPPLIER_ID_LINKED_TEXT.getAttr(), PurchaseInstockEnum.SUPPLIER_ID.getFieldType());
                break;
            case RED_CONTRACT_INSTOCK:
                showFormatHelp.formatLinkBusiness4Show(result, RefundInstockEnum.CUSTOMER_ID.getAttr(), RefundInstockEnum.CUSTOMER_ID_LINKED_TEXT.getAttr(), RefundInstockEnum.CUSTOMER_ID.getFieldType());
                break;
            default:
                break;
        }

        // 格式化关联单据字段
        showFormatHelp.formatLinkBusiness4Show(result, InstockEnum.REF_ID.getAttr(), InstockEnum.REF_ID_LINKED_TEXT.getAttr(), InstockEnum.REF_ID.getFieldType());
    }

    @Override
    public void getProductList(String corpid, List<InstockProductEntity> instockProductList, List<ProductStockInfoEntity> productStockInfoList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 获取前端返回的产品成本
            Double cost = getDoubleOrDefaultFromFormData(productArrayJSONObject, StringConstant.PRODUCT_COST, 0D);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            // 入库仓库
            JSONObject warehouse = FastJsonHelper.getJsonObjectFromFormData(productArrayJSONObject, RelativeProductEnum.WAREHOUSE.getSaasAttr());
            Long warehouseId = 0L;
            if (warehouse != null && warehouse.size() > 0) {
                warehouseId = FastJsonHelper.getLongOrDefaultFromFormData(warehouse, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            }
            // 批次
            String batch = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.BATCH.getSaasAttr(), "");
            // 生产日期
            Long date = DateTimeUtil.getInt(FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.PRODUCE_DATE.getSaasAttr(), ""), DateUtil.SDFDate);
            // 保质期 存的是天数
            Long guaranteePeriod = FastJsonHelper.getLongFromFormData(productArrayJSONObject, RelativeProductEnum.GUARANTEE_PERIOD.getSaasAttr());
            // 产品备注
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.MEMO.getSaasAttr(), "");
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getAttr(), 0D);
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                InstockProductEntity productEntity = new InstockProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductUnit(unit);
                productEntity.setProductNo(productNo);
                productEntity.setProductPrice(price);
                productEntity.setProductSpecification(specification);
                productEntity.setCost(cost);
                productEntity.setWarehouseId(warehouseId);
                productEntity.setSort(sort);
                productEntity.setBatch(batch);
                //JSONObject jsonObject = new JSONObject();
                if (guaranteePeriod != null) {
                    productEntity.setGuaranteePeriod(guaranteePeriod * 86400);
                    //jsonObject.put(InstockProductEnum.GUARANTEE_PERIOD.getAttr(), guaranteePeriod * 86400);
                }
                productEntity.setProduceDate(date);
                productEntity.setMemo(memo);
                instockProductList.add(productEntity);
                // 增加关联id 为了和baseInfo有关联
            }
        }
    }

    @Override
    public void formatNewProductList(String corpid, List<InstockProductEntity> instockProductEntityList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            sort++;
            JSONObject pageProductObject = productArray.getJSONObject(i);
            Long pageProductId = pageProductObject.getLong(InstockProductEnum.PRODUCT.getAttr());
            Double stock = getDoubleOrDefaultFromFormData(pageProductObject, InstockProductEnum.STOCK.getAttr(), 0D);
            Double productNum = getDoubleOrDefaultFromFormData(pageProductObject, InstockProductEnum.NUM.getAttr(), 0D);
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(pageProductObject, InstockProductEnum.MEMO.getAttr(), "");
            String batch = FastJsonHelper.getStringOrDefaultFromFormData(pageProductObject, InstockProductEnum.BATCH.getAttr(), "");
            Long date = FastJsonHelper.getLongOrDefaultFromFormData(pageProductObject, InstockProductEnum.PRODUCE_DATE.getAttr(), 0L);
            Long guaranteePeriod = FastJsonHelper.getLongOrDefaultFromFormData(pageProductObject, InstockProductEnum.GUARANTEE_PERIOD.getAttr(), 0L);
            Double cost = getDoubleOrDefaultFromFormData(pageProductObject, InstockProductEnum.COST.getAttr(), 0D);
            SaveFormatHelp.formatLinkBusiness4Save(pageProductObject,InstockProductEnum.WAREHOUSE.getAttr(), "warehouseName", FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
            Long warehouseId = pageProductObject.getLong(InstockProductEnum.WAREHOUSE.getAttr());
            Long subProductId = FastJsonHelper.getLongFromFormData(pageProductObject, BusinessConstant.PRODUCT_SUB_ID);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getAttr(), 0D);
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                InstockProductEntity productEntity = new InstockProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setWarehouseId(warehouseId);
                productEntity.setWarehouseName(pageProductObject.getString(WarehouseEnum.WAREHOUSE_NAME.getSaasAttr()));
                productEntity.setProductPrice(price);
                productEntity.setCost(cost);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setProductSpecification(specification);
                productEntity.setProductUnit(unit);
                productEntity.setSort(sort);
                productEntity.setBatch(batch);
                if (Objects.nonNull(subProductId)) {
                    productEntity.setId(subProductId);
                }
                if (guaranteePeriod != null) {
                    productEntity.setGuaranteePeriod(guaranteePeriod * 86400);
                }
                productEntity.setProduceDate(date);
                productEntity.setMemo(memo);
                productEntity.setData(pageProductObject);
                instockProductEntityList.add(productEntity);
            }
        }
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, Boolean forProcess, Integer operate, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        Integer type = data.getInteger(InstockEnum.TYPE.getAttr());
        // 获取关联产品
        List<InstockProductEntity> instockProductEntityList = new ArrayList<>();
        List<ProductStockInfoEntity> productStockInfoList = new ArrayList<>();
        Map<Long, JSONArray> refProductSeqMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> productIdList = new HashSet<>();
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(InstockEnum.PRODUCT.getAttr()) instanceof JSONObject) {
                JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, InstockEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(productIdList, corpid, productArr);
                getProductList(corpid, instockProductEntityList, productStockInfoList, productArr, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(InstockEnum.PRODUCT.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    List<Long> productIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        // 页面传入的产品的id
                        Long productId = object.getLong(InstockProductEnum.PRODUCT.getAttr());
                        if (Objects.nonNull(productId)) {
                            productIdIn.add(productId);
                            productIdList.add(productId);
                        }
                    }
                    // 获取产品信息
                    Map<Long, ProductEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    if (productIdIn.size() >= 1) {
                        // 从产品表中获取对应的产品信息
                        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        params.put("corpid", corpid);
                        params.put("idIn", productIdIn);
                        params.put("del", 0);
                        List<ProductEntityExt> productModelEntitys = productModel.findEntitys(params);
                        if (productModelEntitys != null) {
                            for (ProductEntityExt entity : productModelEntitys) {
                                productMap.put(entity.getId(), entity);
                            }
                        }
                    }
                    formatNewProductList(corpid, instockProductEntityList, jsonArray, productMap);
                }
            }
        } else {
            // 检索del=0和del=6的数据，del=6是工作流中审批节点拒绝和撤回产生的数据，不是通过审批拒绝、撤回的数据不会产生del=6的数据，如果拒绝和撤回重新提交后，del=6将会被置回del=0

            instockProductEntityList = instockProductModel.getProductsByInstockIdIn(corpid, dataId, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
            if (commonHelp.isOpenWorkFlow(corpid) && Objects.nonNull(forProcess) && forProcess && Objects.equals(WorkflowOperateEnum.ADD.getType(), operate)) {
                // 工作流的详情，需要从上下文中拼接序列号数据
                JSONArray productArray = data.getJSONArray(InstockEnum.PRODUCT.getAttr());
                for (int i = 0; i < productArray.size(); i++) {
                    JSONObject jsonObject = productArray.getJSONObject(i);
                    refProductSeqMap.put(jsonObject.getLong(BusinessConstant.PRODUCT_SUB_ID), jsonObject.getJSONArray(ProductConstant.SEQ));
                }
            } else {
                // 表单序列号流水
                List<ProductSerialFlowEntity> productSerialFlowList = productSerialFlowModel.getFlowByRefIdAndBusiness(Collections.singletonList(dataId), InstockTypeEnum.getStockBusinessTypeByCode(type), corpid);
                for (ProductSerialFlowEntity entity : productSerialFlowList) {
                    JSONArray serialArray = refProductSeqMap.getOrDefault(entity.getRefProductId(), new JSONArray());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(SerialEnum.SERIAL.getAttr(), entity.getSeq());
                    jsonObject.put(SerialEnum.MEMO.getAttr(), entity.getMemo());
                    serialArray.add(jsonObject);

                    refProductSeqMap.put(entity.getRefProductId(), serialArray);
                }

            }
            instockProductEntityList.forEach(item -> {
                productIdList.add(item.getProductId());
                JSONArray seqArray = refProductSeqMap.getOrDefault(item.getId(), null);
                if (Objects.nonNull(seqArray)) {
                    item.getData().put(ProductConstant.SEQ, seqArray);
                }
            });
        }
        Set<String> batchKeyList = new HashSet<>();
        Set<Long> warehouseIdList = new HashSet<>();
        Set<String> warehouseKeySet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        instockProductEntityList.forEach(item -> {
            warehouseKeySet.add(item.getProductId() + "_" + item.getWarehouseId());
            warehouseIdList.add(item.getWarehouseId());
            if (StringUtil.isNotEmpty(item.getBatch())) {
                String key = BatchKeyHelp.getBatchKey(item.getProductId(), item.getWarehouseId(), item.getBatch(), item.getProduceDate(), item.getGuaranteePeriod());
                batchKeyList.add(key);
            }
        });

        Map<String, Double> productWarehouseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, String> warehouseNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!productIdList.isEmpty() && !warehouseIdList.isEmpty()) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put(ParameterConstant.CORPID, corpid);
//            params.put("productIdIn", productIdList);
//            params.put("warehouseIdIn", warehouseIdList);
            params.put("warehouseKeyIn",warehouseKeySet);
            List<ProductWarehouseEntity> productWarehouseEntities = productWarehouseModel.findEntitysWithWarehouseChecked(params,null);
            productWarehouseEntities.forEach(item -> {
                String key = item.getProductId() + "_" + item.getWarehouseId();
                productWarehouseMap.put(key, item.getNum());
            });
        }
        if (!warehouseIdList.isEmpty()) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put(ParameterConstant.CORPID, corpid);
            params.put("idIn",warehouseIdList);
            List<WarehouseEntityExt> warehouseEntityExtList = warehouseModel.findEntitys(params);
            warehouseEntityExtList.forEach(item ->  warehouseNameMap.put(item.getId(),item.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr())));
        }

        // 批次库存
        Map<String, Double> productBatchWarehouseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!batchKeyList.isEmpty()) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put(ParameterConstant.CORPID, corpid);
            params.put("batchKeyIn", batchKeyList);
            List<ProductStockEntity> productStockEntities = productStockModel.findEntitys(params);
            productStockEntities.forEach(item -> {
                productBatchWarehouseMap.put(item.getBatchKey(), item.getNum());
            });
        }
        JSONArray productArray = new JSONArray();
        for (InstockProductEntity instockProductEntity : instockProductEntityList){
            JSONObject json = formatSingleProduct(instockProductEntity);
            String key;
            if (StringUtil.isEmpty(json.getString(SelectProductEnum.BATCH.getAttr()))) {
                key = instockProductEntity.getProductId() + "_" + instockProductEntity.getWarehouseId();
                json.put(InstockProductEnum.STOCK.getAttr(), productWarehouseMap.getOrDefault(key, 0D));
            }else {
                key = BatchKeyHelp.getBatchKey(instockProductEntity.getProductId(), instockProductEntity.getWarehouseId(), instockProductEntity.getBatch(), instockProductEntity.getProduceDate(), instockProductEntity.getGuaranteePeriod());
                json.put(InstockProductEnum.STOCK.getAttr(), productBatchWarehouseMap.getOrDefault(key, 0D));
            }


            if (updateDataTypeEnum.isUpdate()){
                json.put(BusinessConstant.PRODUCT_SUB_ID,instockProductEntity.getId());
                if (Objects.isNull(instockProductEntity.getId())) {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
            }else {
                json.put(BusinessConstant.PRODUCT_SUB_ID,0);
            }
            if (updateDataTypeEnum.isLinkAdd()){
                json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(instockProductEntity.getCorpid(),instockProductEntity.getProductUnit()));
            }
            JSONObject warehouseObj = new JSONObject();
            warehouseObj.put("id",instockProductEntity.getWarehouseId());
            warehouseObj.put("name", Objects.isNull(warehouseNameMap.get(instockProductEntity.getWarehouseId())) ? instockProductEntity.getWarehouseName() : warehouseNameMap.get(instockProductEntity.getWarehouseId()));
            json.put(InstockProductEnum.WAREHOUSE.getAttr(),Collections.singletonList(warehouseObj));
            // 源单编号字段，移动端顶部渲染需要
            if (json.containsKey(SelectProductEnum.SOURCE_DOC.getAttr())) {
                json.put(SelectProductEnum.SOURCE_SOURCE_DOC.getAttr(), json.get(SelectProductEnum.SOURCE_DOC.getAttr()));
            }
            if (Objects.equals(type, InstockTypeEnum.PURCHASE_INSTOCK.getCode())) {
                json.put(SelectProductEnum.SOURCE_PRICE.getAttr(),json.getDouble(SelectProductEnum.COST.getAttr()));
            }
            if (Objects.equals(type, InstockTypeEnum.RED_CONTRACT_INSTOCK.getCode())) {
                json.put(SelectProductEnum.SOURCE_PRICE.getAttr(),json.getDouble(SelectProductEnum.PRICE.getAttr()));
            }
            json.put("refId",instockProductEntity.getId());
            productArray.add(json);
        }
        data.put(InstockEnum.PRODUCT.getAttr(),productArray);
    }

    @Override
    public JSONObject formatSingleProduct(InstockProductEntity instockProductEntity) {
        JSONObject json = instockProductEntity.getData();
        showFormatHelp.approvalSetBusinessUnit(json, instockProductEntity);
        if (Objects.isNull(json) || json.isEmpty()){
            json = new JSONObject();
            for (InstockProductEnum instockProductEnum : InstockProductEnum.values()){
                String attr = instockProductEnum.getAttr();
                switch (instockProductEnum){
                    case PRODUCT:
                        json.put(attr,instockProductEntity.getProductId());
                        break;
                    case WAREHOUSE:
                        json.put(attr,instockProductEntity.getWarehouseId());
                        break;
                    case NUM:
                        json.put(attr,instockProductEntity.getProductNum());
                        break;
                    case COST:
                        json.put(attr,instockProductEntity.getCost());
                        break;
                    case TOTAL_COST:
                        json.put(attr,instockProductEntity.getCost() * instockProductEntity.getProductNum());
                        break;
                    case MEMO:
                        json.put(attr,instockProductEntity.getMemo());
                        break;
                    case UNIT:
                        json.put(attr, instockProductEntity.getProductUnit());
                        break;
                    case PRODUCE_DATE:
                        json.put(attr,instockProductEntity.getProduceDate());
                        break;
                    case GUARANTEE_PERIOD:
                        if (Objects.nonNull(instockProductEntity.getGuaranteePeriod()) && !Objects.equals(instockProductEntity.getProduceDate(), 0L)) {
                            json.put(attr, Arith.div(instockProductEntity.getGuaranteePeriod(), TimeConstant.SECONDS_PER_DAY));
                        }
                        break;
                    case EXPIRE_DATE:
                        if (Objects.nonNull(instockProductEntity.getGuaranteePeriod()) && Objects.nonNull(instockProductEntity.getProduceDate())) {
                            json.put(attr, Arith.add(instockProductEntity.getProduceDate(), instockProductEntity.getGuaranteePeriod()));
                        }
                        break;
                    case BATCH:
                        json.put(attr,instockProductEntity.getBatch());
                        break;
                    default:
                        break;
                }
            }
        } else if (Objects.equals(json.getDouble(SelectProductEnum.GUARANTEE_PERIOD.getAttr()), 0D)) {
            if (Objects.equals(instockProductEntity.getProduceDate(), 0L) || Objects.isNull(instockProductEntity.getProduceDate())) {
                json.remove(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
            }
        }
        return json;
    }

    @Override
    public List<PaasFormDataEntityExt> findInstockList(String corpid, Integer type, Long refId, List<Integer> flowStatusIn, List<String> fieldList) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        String esData = StringConstant.JSON_DATA + StringConstant.POINT;
        boolQueryBuilder.filter(termQuery(esData + InstockEnum.REF_ID.getAttr(), refId));
        boolQueryBuilder.filter(termQuery(esData + InstockEnum.TYPE.getAttr(), type));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), flowStatusIn));
        boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        return esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_INSTOCK, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
    }

}
